var session = sessionStorage.getItem("session");
if (!session) {
	window.parent.location = "../../login.html";
}
$(document).ready(function() {
	getTaskType();
	jQuery("#jqGrid").jqGrid({
		url: IP + "/QueryByProbe?callback=?&session=a",
		datatype: "jsonp",
		colModel: [{
			label: '序号',
			sorttype: 'integer',
			name: 'id',
			key: true,
			width: 50
		}, {
			label: '探针编号',
			name: 'deviceid',
			width: 120
		}, {
			label: '任务类型',
			name: 'type',
			width: 120
		}, {
			label: '设备组名',
			name: 'devgroupname',
			width: 120
		}, {
			label: '任务模板名称',
			name: 'modelname',
			width: 120
		}, {
			label: '安装地址',
			name: 'install',
			width: 120
		}, {
			label: '成功率',
			name: 'success_rate',
			width: 120
		}, {
			label: '平均延时',
			name: 'avgLatency',
			width: 120
		}, {
			label: '失败次数',
			name: 'losstimes',
			width: 120
		}, {
			label: '总次数',
			name: 'alltimes',
			width: 120
		}, {
			label: '得分',
			name: 'quality_score',
			width: 120
		}],
		loadonce: true,
		height: 350,
		rowNum: 13,
		page: 1,
		viewrecords: true,
		pagerpos: 'center',
		pgbuttons: true,
		pginput: true,
		loadtext: '正在加载数据',
		pager: "#jqGridPager"
	});
});

function check() {
	if ($("#probeDetail").val() == "") {
		$.messager.show({
			title: '提示！',
			msg: '请选择探针编号！',
			showType: 'fade',
			style: {
				right: '',
				bottom: ''
			}
		});
		return false;
	} else if (document.getElementById("taskType").value == "") {
		$.messager.show({
			title: '提示！',
			msg: '请选择任务类型！',
			showType: 'fade',
			style: {
				right: '',
				bottom: ''
			}
		});
		return false;
	} else if ($("#sDate").datetimebox("getValue") == "") {
		$.messager.show({
			title: '提示！',
			msg: '请选择开始时间！',
			showType: 'fade',
			style: {
				right: '',
				bottom: ''
			}
		});
		return false;
	} else if ($("#eDate").datetimebox("getValue") == "") {
		$.messager.show({
			title: '提示！',
			msg: '请选择结束时间！',
			showType: 'fade',
			style: {
				right: '',
				bottom: ''
			}
		});
		return false;
	} else if ($("#sj").val() == "") {
		$.messager.show({
			title: '提示！',
			msg: '请选择时间粒度！',
			showType: 'fade',
			style: {
				right: '',
				bottom: ''
			}
		});
		return false;
	}
}

function find() {
	if (check() == false) {
		return;
	};
	jQuery("#jqGrid").jqGrid({
		url: IP + "/QueryByProbe?callback=?&session=" + session + "&device=" + $("#probeDetail").val() + "&tasktype=" + document.getElementById("taskType").value + "&sdate=" + $("#sDate").datetimebox("getValue") + "&edate=" + $("#eDate").datetimebox("getValue") + "&sj=" + $("#sj").val() + "&unit=" + document.getElementById("unit").value,
		datatype: "jsonp",
		colModel: [{
			label: '序号',
			sorttype: 'integer',
			name: 'id',
			key: true,
			width: 50
		}, {
			label: '探针编号',
			name: 'deviceid',
			width: 120
		}, {
			label: '任务类型',
			name: 'type',
			width: 120
		}, {
			label: '设备组名',
			name: 'devgroupname',
			width: 120
		}, {
			label: '任务模板名称',
			name: 'modelname',
			width: 120
		}, {
			label: '安装地址',
			name: 'install',
			width: 120
		}, {
			label: '成功率',
			name: 'success_rate',
			width: 120
		}, {
			label: '平均延时',
			name: 'avgLatency',
			width: 120
		}, {
			label: '失败次数',
			name: 'losstimes',
			width: 120
		}, {
			label: '总次数',
			name: 'alltimes',
			width: 120
		}, {
			label: '得分',
			name: 'quality_score',
			width: 120
		}],
		loadonce: true,
		height: 350,
		rowNum: 13,
		page: 1,
		viewrecords: true,
		pagerpos: 'center',
		pgbuttons: true,
		pginput: true,
		loadtext: '正在加载数据',
		pager: "#jqGridPager"
	});
	showHistogram();
	showPie();
};

function showHistogram() {
	var chart = {
		type: 'column'
	};
	var title = {
		text: '每月平均降雨量'
	};
	var subtitle = {
		text: 'Source: runoob.com'
	};
	var xAxis = {
		categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
		crosshair: true
	};
	var yAxis = {
		min: 0,
		title: {
			text: 'Rainfall (mm)'
		}
	};
	var tooltip = {
		headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
		pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
			'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
		footerFormat: '</table>',
		shared: true,
		useHTML: true
	};
	var plotOptions = {
		column: {
			pointPadding: 0.2,
			borderWidth: 0
		}
	};
	var credits = {
		enabled: false
	};

	var series = [{
		name: 'Tokyo',
		data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
	}, {
		name: 'New York',
		data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3]
	}, {
		name: 'London',
		data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2]
	}, {
		name: 'Berlin',
		data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1]
	}];

	var json = {};
	json.chart = chart;
	json.title = title;
	json.subtitle = subtitle;
	json.tooltip = tooltip;
	json.xAxis = xAxis;
	json.yAxis = yAxis;
	json.series = series;
	json.plotOptions = plotOptions;
	json.credits = credits;
	$('#container').highcharts(json);
};

function showPie() {
	var chart = {
		plotBackgroundColor: null,
		plotBorderWidth: null,
		plotShadow: false
	};
	var title = {
		text: 'Browser market shares at a specific website, 2014'
	};
	var tooltip = {
		pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
	};
	var plotOptions = {
		pie: {
			allowPointSelect: true,
			cursor: 'pointer',
			dataLabels: {
				enabled: false
			},
			showInLegend: true
		}
	};
	var series = [{
		type: 'pie',
		name: 'Browser share',
		data: [
			['Firefox', 45.0],
			['IE', 26.8], {
				name: 'Chrome',
				y: 12.8,
				sliced: true,
				selected: true
			},
			['Safari', 8.5],
			['Opera', 6.2],
			['Others', 0.7]
		]
	}];

	var json = {};
	json.chart = chart;
	json.title = title;
	json.tooltip = tooltip;
	json.series = series;
	json.plotOptions = plotOptions;
	$('#container1').highcharts(json);
};

function showDialog() {
	$("#probeTable").dialog("open");
	jQuery("#pGrid").jqGrid({
		url: IP + "GetProbeInfoList?callback=?&session=" + session,
		datatype: "jsonp",
		height: 230,
		width: 260,
		colNames: ['设备名称', '设备唯一编码'],
		colModel: [{
			name: 'deviceName',
			index: 'deviceName',
			sopt: ['eq'],
			width: 30
		}, {
			name: 'deviceid',
			index: 'deviceid',
			sopt: ['eq'],
			width: 40
		}],
		autowidth: false,
		shrinkToFit: true,
		//		shrinkToFit:false,
		loadonce: true,
		mtype: "GET",
		multiselect: true,
		multiselectWidth: 20,
		page: 1,
		colMenu: true,
		viewrecords: true
			//		sortorder: "asc",
			//		sortname: 'id'
	});
	var timer;
	$("#SearchCellPingId").on("keyup", function() {
		var self = this;
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(function() {
			//timer = null;
			$("#pGrid").jqGrid('filterInput', self.value);
		}, 0);
	});

};

//选取弹针类型；
function searchProbe(current, at, state) {
	$("#probeDetail").empty();
	var arr = [];
	var Ids = $(current).jqGrid("getGridParam", "selarrrow");
	var len = Ids.length
	if (len == 0) {
		$.messager.show({
			title: '提醒',
			msg: '您什么也没选',
			timeout: 1300,
			showType: 'slide',
			style: {
				right: '',
				bottom: ''
			}
		});
		return false;
	} else {
		for (var i = 0; i < len; i++) {
			var getRow = $(current).getRowData(Ids[i]);
			arr.push(getRow[at]);
		}
		var str = arr.join(",");
		$("#probeDetail").textbox('setValue', str);
		$("#probeTable").dialog("close");
		$(current).trigger("reloadGrid");
		flag = state;
	}
};

function getTaskType() {
	$.ajax({
		url:   IP+"GetSystemParam?&callback=?&flag=1001" + "&session=" + session,
		type: "Get",
		dataType: "jsonp",
		jsonp: "callback",
		jsonpCallback: "resultHandler",
		success: function(data) {
			var options = data.vValue.split(",");
			var frag = document.createDocumentFragment("fragElement");
			var op = document.createElement("OPTION");
			op.text = "All";
			frag.appendChild(op);
			for (var i = 0; i < options.length; i++) {
				var opObj = document.createElement("OPTION");
				opObj.text = options[i];
				opObj.value = options[i];
				frag.appendChild(opObj);
			}
			$("#taskType").append(frag);
		}
	});

};

function export1() {
	var title = "探针质量统计呈现";
	getXlsFromTbl('jqGrid', 'div_list', title, true);
};

//导出excel
function getXlsFromTbl(inTblId, inTblContainerId, title, rownumbers) {
	try {
		var allStr = "";
		var curStr = "";
		//alert("getXlsFromTbl");  
		if (inTblId != null && inTblId != "" && inTblId != "null") {
			curStr = getTblData($('#' + inTblId), $('#' + inTblContainerId), rownumbers);
		}
		if (curStr != null) {
			allStr += curStr;
		} else {
			alert("你要导出的表不存在！");
			return;
		}
		var fileName = getExcelFileName(title);
		doFileExport(fileName, allStr);
	} catch (e) {
		alert("导出发生异常:" + e.name + "->" + e.description + "!");
	}
};

function getTblData(curTbl, curTblContainer, rownumbers) {

	var outStr = "";
	if (curTbl != null) {
		var rowdata = curTbl.getRowData();
		var Lenr = 1;

		for (i = 0; i < Lenr; i++) {
			//var Lenc = curTbl.rows(i).cells.length;  
			var th;
			if (rownumbers == true) {
				th = curTblContainer.find('TH:not(:first-child)');
			} else {
				th = curTblContainer.find('TH');
			}
			th.each(function(index, element) {
				//alert($(element).text());  
				//取得每行的列数  
				var j = index + 1;
				var content = $(element).text();
				//alert(j + "|" + content);  
				outStr += content + "\t";
				//赋值  

			});
			outStr += "\r\n";
		}
		var tmp = "";
		for (i = 0; i < rowdata.length; i++) {
			var row = eval(rowdata[i]);
			for (each in row) {
				outStr += row[each] + "\t";
			}
			outStr += "\r\n";
		}


	} else {
		outStr = null;
		alert(inTbl + "不存在!");
	}
	return outStr;
};

function getExcelFileName(title) {
	var d = new Date();
	var curYear = d.getYear();
	var curMonth = "" + (d.getMonth() + 1);
	var curDate = "" + d.getDate();
	var curHour = "" + d.getHours();
	var curMinute = "" + d.getMinutes();
	var curSecond = "" + d.getSeconds();
	if (curMonth.length == 1) {
		curMonth = "0" + curMonth;
	}
	if (curDate.length == 1) {
		curDate = "0" + curDate;
	}
	if (curHour.length == 1) {
		curHour = "0" + curHour;
	}
	if (curMinute.length == 1) {
		curMinute = "0" + curMinute;
	}
	if (curSecond.length == 1) {
		curSecond = "0" + curSecond;
	}
	var fileName = title + "_" + curYear + curMonth + curDate + "_" + curHour + curMinute + curSecond + ".csv";
	//alert(fileName);   
	return fileName;
};

function doFileExport(inName, inStr) {
	var xlsWin = null;
	if (!!document.all("HideFrm")) {
		xlsWin = HideFrm;
	} else {
		var width = 6;
		var height = 4;
		var openPara = "left=" + (window.screen.width / 2 - width / 2) + ",top=" + (window.screen.height / 2 - height / 2) + ",scrollbars=no,width=" + width + ",height=" + height;
		xlsWin = window.open("", "_blank", openPara);
	}
	xlsWin.document.write(inStr);
	xlsWin.document.close();
	xlsWin.document.execCommand('Saveas', true, inName);
	xlsWin.close();
};